package cheme.ProcessModel.Equations;

import java.io.IOException;
import java.io.Serializable;

import cheme.ProcessModel.AbstractParent;
import cheme.ProcessModel.ChemePropertyChangeEvent;
import cheme.ProcessModel.IChild;
import cheme.ProcessModel.IModelElement;
import cheme.ProcessModel.IPropertyAware;
import cheme.ProcessModel.ModelEnv;
import cheme.ProcessModel.ProcessModelConstants;
import cheme.ProcessModel.Table.IRow;
import cheme.ProcessModel.Visitors.IModelVisitor;

public class EquationList extends AbstractParent<IRow> implements Serializable
{
	/*
	 * Serialization version identifier. (Set to default for now)
	 */
	
	private static final long serialVersionUID = 1L;
		
	public EquationList(IModelElement parent)
	{
		super(parent);
		
		add((Equation)ModelEnv.getInstanceFor(this).createModelElement(ProcessModelConstants.EQUATION, this));
	}
	
//	private void writeObject(java.io.ObjectOutputStream out) throws IOException
//	{
//	}
	 
	 private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
	 {
		 /*
		  * Make sure the interpreter can listen to my changes.
		  * Specifically, when an equation is added to this list, the addition needs to
		  * trigger an initial interpretation of that component. Likewise, removal needs to be processed.
		  */
		 
		 ModelEnv.getInstanceFor(this).hookModelElement(this);
		 
		 /*
		  * Make sure I can listen to my children created form a past session.
		  */
		 
		 for(IChild child : getChildren())
		 {
			 child.addPropertyChangeListener(this);
		 }
	 }

	@Override
	protected void unhookChild(IRow child)
	{
		ModelEnv.getInstanceFor(this).unhookModelElement(child);
		super.unhookChild(child);
	}
	
	/*
	 * Note that this is intercepting the fireing of events due to adding or removing equation tokens, 
	 * this method does not respond to events from the child tokens.
	 */
	@Override
	public void firePropertyChange(ChemePropertyChangeEvent evt)
	{
		super.firePropertyChange(evt);
		
		if(evt.getPropertyName().equals(IPropertyAware.P_CHILD) || //change in children set membership--common, this one.
			evt.getPropertyName().equals(IPropertyAware.P_CHILDREN))//ditto
		{
			super.firePropertyChange(
					new ChemePropertyChangeEvent(this, P_INTERPRETABLE, evt.getOldValue(), evt.getNewValue(), evt));
		}
	}
	
	public Object accept(IModelVisitor ruleChecker)
	{
		return ruleChecker.visit(this);
	}
}